import { AnyAction, Reducer } from 'redux';
import { message } from 'antd';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';
import { querylogisticsCenterList, operChangeStatus } from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    change: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'logisticsCenterList',

  state: {
    dataInfo: {
      count: 0,
      list: [],
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(querylogisticsCenterList, payload);
      yield put({
        type: 'save',
        payload: response.body,
      });
    },

    * change({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operChangeStatus, query);
      const data = fetchValidation(response);
      if (data) {
        message.success(query.status === 1 ? '启用成功' : '禁用成功');
        yield put({
          type: 'fetch',
          payload: search,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },
  },
};

export default Model;
